package com.lvmama.pangolin.util;

import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.entity.hotel.HotelCommodityDetail;
import com.lvmama.pangolin.entity.hotel.HotelProductDetail;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 酒店产品关联匹配工具类
 * <h1>排序权重比例：NAME_WEIGHT，CITYCODE_WEIGHT</h1>
 * <p>由于酒店名称作为匹配度最为重要的因素，同时，城市也是进行酒店匹配的重要因素之一</p>
 */
@Component
public class ProductRelationshipHotelUtil {
    private static final Logger logger = Logger.getLogger(ProductRelationshipHotelUtil.class);

    @Autowired
    private CommodityMatchUtil commodityMatchUtil;

    private static final String NONE="";

    /**
     * 酒店产品名称所占权重
     */
    private float getNameWeightProd()
    {
        String _NAME_WEIGHT = ConfigManager.getInstance().getParamValue("HOTEL_NAME_WEIGHT","HOTEL_NAME_WEIGHT");
        return (_NAME_WEIGHT!=null &&!"".equals(_NAME_WEIGHT))?Float.valueOf(_NAME_WEIGHT):0.9f;
    }

    /**
     * 酒店产品所在城市所占权重
     */
    private float getCityCodeWeightProd()
    {
        String _CITYCODE_WEIGHT = ConfigManager.getInstance().getParamValue("HOTEL_CITYCODE_WEIGHT","HOTEL_CITYCODE_WEIGHT");
        return (_CITYCODE_WEIGHT!=null && !"".equals(_CITYCODE_WEIGHT))?Float.valueOf(_CITYCODE_WEIGHT):0.1f;
    }

    /**
     * 获取酒店商品名称所占权重
     * @return
     */
    private float getNameWeightCommodity()
    {
        String _NAME_WEIGHT = ConfigManager.getInstance().getParamValue("HOTEL_NAME_WEIGHT_COMMODITY","HOTEL_NAME_WEIGHT_COMMODITY");
        return (_NAME_WEIGHT!=null && !"".equals(_NAME_WEIGHT))?Float.valueOf(_NAME_WEIGHT):0.6f;
    }
    /**
     * 获取酒店商品城市所占权重
     * @return
     */
    private float getCityCodeWeightCommodity()
    {
        String _CITYCODE = ConfigManager.getInstance().getParamValue("HOTEL_CITYCODE_WEIGHT_COMMODITY","HOTEL_CITYCODE_WEIGHT_COMMODITY");
        return (_CITYCODE!=null && !"".equals(_CITYCODE))?Float.valueOf(_CITYCODE):0.1f;
    }
    /**
     * 获取酒店商品价格所占权重
     * @return
     */
    private float getPriceWeightCommodity()
    {
        String _PRICE = ConfigManager.getInstance().getParamValue("HOTEL_PRICE_WEIGHT_COMMODITY","HOTEL_PRICE_WEIGHT_COMMODITY");
        return (_PRICE!=null && !"".equals(_PRICE))?Float.valueOf(_PRICE):0.2f;
    }
    /**
     * 获取酒店商品房型所占权重
     * @return
     */
    private float getRoomTypeWeightCommodity()
    {
        String _ROOMTYPE = ConfigManager.getInstance().getParamValue("HOTEL_ROOMTYPE_WEIGHT_COMMODITY","HOTEL_ROOMTYPE_WEIGHT_COMMODITY");
        return (_ROOMTYPE!=null && !"".equals(_ROOMTYPE))?Float.valueOf(_ROOMTYPE):0.1f;
    }

    /**
     * 酒店产品列表与驴妈妈酒店进行比对排序
     * @param hotels
     * @param lvmmHotel
     */
    public void sortHotelProduct(List<HotelProductDetail> hotels,HotelProductDetail lvmmHotel)
    {
        try {
            if(hotels==null || hotels.isEmpty() || lvmmHotel==null|| StringUtils.isEmpty(lvmmHotel.getHotelName()))
            {
                return;
            }
            Map<String,String> mapLvmama = commodityMatchUtil.preHandelString(lvmmHotel.getHotelName());//字符串进行预处理
            if(mapLvmama==null)
            {
                return;
            }
            String _lvmama_preName = mapLvmama.get("preName");
            String _lvmama_segName = mapLvmama.get("segName");
            Map<String,String> temp = null;
            String _temp_preName = null;
            String _temp_segName = null;
            for(HotelProductDetail hotel:hotels)
            {
                if(hotel==null||StringUtils.isEmpty(hotel.getHotelName()))
                {
                    continue;
                }
                temp = commodityMatchUtil.preHandelString(hotel.getHotelName());
                if(temp==null)
                {
                    continue;
                }
                _temp_preName = temp.get("preName");
                _temp_segName = temp.get("segName");
                if(_lvmama_preName.equals(_temp_preName)||_lvmama_segName.equals(_temp_segName))
                {
                    hotel.setSortScore(1f);
                }else
                {
                    float nameScore = commodityMatchUtil.score(_lvmama_segName,_temp_segName);
                    float cityCodeScore = 0f;
                    if(lvmmHotel.getCityCode()!=null&&lvmmHotel.getCityCode().equals(hotel.getCityCode()))
                    {
                        cityCodeScore = 1f;
                    }
                    float score = nameScore*getNameWeightProd()+cityCodeScore*getCityCodeWeightProd();
                    hotel.setSortScore(score);
                }
            }
        }catch (Exception e)
        {
            logger.error("排序发生异常"+e.getMessage());
        }finally {
            sortHotelProductDetailBySortScore(hotels);
            sortHotelProductDetailByIsLinked(hotels);
        }


    }

    /**
     * 根据sortScore排序
     * @param list
     */
    public void sortHotelProductDetailBySortScore(List<HotelProductDetail> list)
    {
        Collections.sort(list, new Comparator<HotelProductDetail>() {
        @Override
        public int compare(HotelProductDetail o1, HotelProductDetail o2) {
            int temp = 0;
            if(o1.getSortScore() >o2.getSortScore())
            {
                temp = -1;
            }
            else if(o1.getSortScore() < o2.getSortScore())
            {
                temp = 1;
            }
            return temp;
        }
    });
    }

    public void sortHotelProductDetailByIsLinked(List<HotelProductDetail> list)
    {
        Collections.sort(list, new Comparator<HotelProductDetail>() {
            @Override
            public int compare(HotelProductDetail o1, HotelProductDetail o2) {
                if(o1.getIsLink()>o2.getIsLink())
                {
                    return 1;
                }else if(o1.getIsLink()==o2.getIsLink())
                {
                    return 0;
                }else
                {
                    return -1;
                }
            }
        });
    }

    /**
     * 按照与lmmHotelCommodity关联度由高到低对list进行排序
     * @param list
     * @param lmmHotelCommodity
     */
    public void sortHotelCommodity(List<HotelCommodityDetail> list ,HotelCommodityDetail lmmHotelCommodity)
    {
        if(list==null||list.isEmpty()||lmmHotelCommodity==null||StringUtils.isEmpty(lmmHotelCommodity.getCommodityName()))
        {
            return;
        }

        try {
            String[] needRemove = ConfigManager.getInstance().getParamValue("NEEDREMOVE","NEEDREMOVE").split(",");
            String preStr = lmmHotelCommodity.getCommodityName()+"|"+lmmHotelCommodity.getCommodityType();//使用房型和商品名称能够获取到更多关于商品的有用信息
//            String preStr = lmmHotelCommodity.getCommodityName()+"|"+lmmHotelCommodity.getRoomType();//使用房型和商品名称能够获取到更多关于商品的有用信息
            removeSpecialStr(needRemove,preStr);//去掉无用的字符
            Map<String,String> mapLvmama = commodityMatchUtil.preHandelString(preStr);//字符串进行预处理
            if(mapLvmama==null)
            {
                return;
            }
            String _lvmama_preName = mapLvmama.get("preName");
            String _lvmama_segName = mapLvmama.get("segName");
            Map<String,String> temp = null;
            String _temp_preName = null;
            String _temp_segName = null;
            for(HotelCommodityDetail hotel:list)
            {
                if(hotel==null||StringUtils.isEmpty(hotel.getCommodityName()))
                {
                    continue;
                }
                String _tempPreStr = hotel.getCommodityName()+"|"+hotel.getCommodityType();
//                String _tempPreStr = hotel.getCommodityName()+"|"+hotel.getRoomType();
                removeSpecialStr(needRemove,_tempPreStr);//去掉无用的字符
                temp = commodityMatchUtil.preHandelString(_tempPreStr);
                if(temp==null)
                {
                    continue;
                }
                _temp_preName = temp.get("preName");
                _temp_segName = temp.get("segName");
                if(_lvmama_preName.equals(_temp_preName)||_lvmama_segName.equals(_temp_segName))
                {
                    hotel.setSortScore(1f);
                }else
                {
                    float nameScore = commodityMatchUtil.score(_lvmama_segName,_temp_segName);
                    float cityCodeScore = 0f;
                    float price = commodityMatchUtil.priceScore(lmmHotelCommodity.getSalePrice(),hotel.getSalePrice());
                    float roomtype = 0f;
//                    if(lmmHotelCommodity.getRoomType().equals(hotel.getRoomType()))
                    if(lmmHotelCommodity.getCommodityType().equals(hotel.getCommodityType()))
                    {
                        roomtype = 1f;
                    }
                    if(lmmHotelCommodity.getCityCode()!=null&&lmmHotelCommodity.getCityCode().equals(hotel.getCityCode()))
                    {
                        cityCodeScore = 1f;
                    }
                    float score = nameScore*getNameWeightCommodity()+cityCodeScore*getCityCodeWeightCommodity()
                            +price*getPriceWeightCommodity()+roomtype*getRoomTypeWeightCommodity();
                    hotel.setSortScore(score);
                }
            }
        }catch (Exception e)
        {
            logger.error("酒店排序发生异常"+e.getMessage());
        }finally {
            sortHotelCommodityBySortScore(list);
            sortHotelCommodityByIsLinked(list);
        }


    }

    /**
     * 根据sortScore进行排序
     * @param list
     */
    public void sortHotelCommodityBySortScore(List<HotelCommodityDetail> list)
    {
        Collections.sort(list, new Comparator<HotelCommodityDetail>() {
            @Override
            public int compare(HotelCommodityDetail o1, HotelCommodityDetail o2) {
                int temp = 0;
                if(o1.getSortScore() >o2.getSortScore())
                {
                    temp = -1;
                }
                else if(o1.getSortScore() < o2.getSortScore())
                {
                    temp = 1;
                }
                return temp;
            }
        });
    }

    /**
     * 根据是否关联进行排序，将已经关联的置于最后
     * @param list
     */
    public void sortHotelCommodityByIsLinked(List<HotelCommodityDetail> list)
    {
        Collections.sort(list, new Comparator<HotelCommodityDetail>() {
            @Override
            public int compare(HotelCommodityDetail o1, HotelCommodityDetail o2) {
                if(o1.getIsLink()>o2.getIsLink())
                {
                    return 1;
                }else if(o1.getIsLink()==o2.getIsLink())
                {
                    return 0;
                }else
                {
                    return -1;
                }
            }
        });
    }

    /**
     * 去掉str中，含有list所包含的字段
     * <p>例如去掉普通大床房中的，“普通”字样</p>
     * @param list
     * @param str
     */
    public void removeSpecialStr(String[] list,String str)
    {
        if(str==null||StringUtils.isEmpty(str)||list==null||list.length==0)
        {
            return;
        }
        for(String string:list)
        {
            str.replaceAll(string,NONE);
        }
    }
}
